package quartz.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import quartz.entity.JobEntity;

@Service
public class ScheduleJobService {
    @Autowired
    private QuartzHelper quartzHelper;
    @Autowired
    private JobEntityService jobEntityService;

    @Transactional
    public void addJob(JobEntity jobEntity) {
        jobEntityService.save(jobEntity);
        quartzHelper.addJob(jobEntity);
    }

    public void pauseJob(String jobEntityId) {
        JobEntity jobEntity = jobEntityService.findById(jobEntityId);
        quartzHelper.pauseJob(jobEntity);
    }

    public void resumeJob(String jobEntityId) {
        JobEntity jobEntity = jobEntityService.findById(jobEntityId);
        quartzHelper.resumeJob(jobEntity);
    }

    @Transactional
    public void deleteJob(String jobEntityId) {
        JobEntity jobEntity = jobEntityService.findById(jobEntityId);
        quartzHelper.deleteJob(jobEntity);
        jobEntityService.deleteById(jobEntityId);
    }

    @Transactional
    public void updateJob(JobEntity jobEntity) {
        JobEntity existedJobEntity = jobEntityService.findById(jobEntity.getId());
        //todo:update existedJobEntity...
        quartzHelper.updateJob(jobEntity);
    }

    public void executeJob(String jobEntityId) {
        JobEntity jobEntity = jobEntityService.findById(jobEntityId);
        quartzHelper.executeJob(jobEntity);
    }

    public void refreshAll() {
        for (JobEntity jobEntity : jobEntityService.findAll()) {
            if (Boolean.TRUE.equals(jobEntity.getIsActive())) {
                quartzHelper.addJob(jobEntity);
            }
        }
    }

    @Transactional
    public void disableJob(String jobEntityId) {
        JobEntity jobEntity = jobEntityService.findById(jobEntityId);
        jobEntity.setIsActive(false);
        jobEntityService.save(jobEntity);
        quartzHelper.deleteJob(jobEntity);
    }

    @Transactional
    public void activateJob(String jobEntityId) {
        JobEntity jobEntity = jobEntityService.findById(jobEntityId);
        jobEntity.setIsActive(true);
        quartzHelper.addJob(jobEntity);
    }
}
